<template>
  <div class="flex justify-center items-center box-border">
    <div
      class="aaa"
      :style="{ width: props.width, height: props.height }"
      ref="barChartDom"
      v-loading="loading"
    ></div>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  markRaw,
  nextTick,
  onBeforeUnmount,
} from "vue";
import * as echarts from "echarts";

const barChartDom = ref(null);
let chartInstance = ref();
let loading = ref(true);
let props = defineProps({
  width: {
    type: String,
    default: "",
  },
  height: {
    type: String,
    default: "",
  },
  models: {
    type: Object,
    default: () => ({}),
  },

  themeColor: {
    type: Array,
    default: () => [],
  },
});
watch(
  [() => props.models, () => props.themeColor],
  () => {
    chartInit();
  },
  { deep: true }
);

watch(
  [() => props.width, () => props.height],
  (newValue) => {
    if (chartInstance.value) {
      resize();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
const states = computed({
  get: () => props.models,
});
onMounted(() => {
  setTimeout(() => {
    loading.value = false;
  }, 300);
  chartInit();
});
const resize = () => {
  nextTick(() => {
    chartInstance.value.resize();
  });
};
onBeforeUnmount(() => {
  chartInstance.value.dispose();
  chartInstance.value = null;
  window.removeEventListener("resize", () => {});
});
function chartInit() {
  if (!chartInstance.value) {
    chartInstance.value = markRaw(echarts.init(barChartDom.value));
  }

  let option = {
    color: props.themeColor,
    ...JSON.parse(JSON.stringify(states.value)),
  };

  option && chartInstance.value.setOption(option, true);
}

defineExpose({
  resize,
  chartInstance: chartInstance,
});
</script>

<style scoped lang="scss">
.charts {
  width: 100%;
  height: 100%;
  margin: 0 auto;
}
</style>
